library(ggplot2)
library(dplyr)
library(reshape2)
library(fst)
library(haven)
library(lm.beta)

load("main_data_local.rdata")

#create function for splitting income residuals in brackets
stacker <- 
  function(x){
    stack <- NA
    stack[x >=-3.25] <- -3
    stack[x > -2.75] <- -2.5
    stack[x > -2.25] <- -2
    stack[x > -1.75] <- -1.5
    stack[x > -1.25] <- -1
    stack[x > - .75] <- -.5
    stack[x > - .25] <- 0
    stack[x >   .25] <- .5
    stack[x >   .75] <- 1
    stack[x >  1.25] <- 1.5
    stack[x >  1.75] <- 2
    stack[x >  2.25] <- 2.5
    stack[x >  2.75] <- 3
    return(stack)
  }

inc_1985 <- 
  read.fst("ind1985.fst")

inc_1986 <- 
  read.fst("ind1986.fst")

inc_1987 <- 
  read.fst("ind1987.fst")

inc <- 
  left_join(inc_1985 %>% select(c("PNR", "SAMLINK_NY")), 
            inc_1986 %>% select(c("PNR", "SAMLINK_NY")), 
            by = "PNR") %>% 
  left_join(., inc_1987 %>% select(c("PNR", "SAMLINK_NY")),
            by = "PNR") %>% 
  mutate(SAMLINK_NY = rowMeans(cbind(SAMLINK_NY.x, SAMLINK_NY.y, SAMLINK_NY), na.rm = TRUE)) %>% 
  select(c("PNR", SAMLINK_NY))

bef_father <-
  read.fst("bef1986.fst") %>% 
  select("PNR", "KOEN", "ALDER")

inc <- 
  left_join(inc, bef_father, by = "PNR")

inc <-
  inc %>%
  filter(KOEN == 1 & ALDER > 17) 

data_out <- tibble()
 
for(k in seq(1993, 2013, by = 4)){
  bef <-
    read.fst(paste("bef", k, ".fst", sep = "")) 
  
  var <- c("run_kv", "VALGT_JN")
  lab <- c("local candidate", "local winner")
  
  koms <- unique(bef$KOM)
  
  for(j in 1:2){
    
  bef_j <- 
    bef %>% 
    select("PNR", "FAR_ID", "KOM")
  
  data_year <- 
    data_comp_local %>% 
    filter(four_years == k) %>% 
    left_join(., bef_j, by = "PNR") %>% 
    left_join(., inc, by = c("FAR_ID" = "PNR")) %>%
    filter(inc_res < quantile(inc_res, p = 0.999) &
             inc_res > quantile(inc_res, p = 0.001) ) %>% 
    filter(first_elected == 0 | first_elected >= k) %>% 
    mutate(inc_res2 = (inc_res - mean(inc_res)) / sd(inc_res)) %>%
    filter(abs(inc_res2) <= 3.25) %>% 
    mutate(inc_res_bars = stacker(inc_res2))
  
    for(kom in koms){
      data_year_i <- 
        data_year %>%
        filter(KOM == kom) %>%
        group_by(KOEN, ALDER) %>% 
        mutate(inc_tile = ntile(SAMLINK_NY, 20)) %>% 
        ungroup()
      
      data_year_i_pol <- 
        data_year_i %>% 
        filter(.[var[j]] == 1)
      
      par_inc_m <- rep(NA, 20)
      par_inc_c <- rep(NA, 20)
      
      inc_res_m <- rep(NA, 13)
      inc_res_c <- rep(NA, 13)
      
      if(nrow(data_year_i_pol) > 3) {
        for(i in 1:20){
          par_inc_m[i] <- mean(data_year_i$inc_tile == i, na.rm = TRUE)
          par_inc_c[i] <- mean(data_year_i_pol$inc_tile == i, na.rm = TRUE)
        }
        for(i in 1:13){
          res <- seq(-3, 3, 0.5)[i]
          inc_res_m[i] <- mean(data_year_i$inc_res_bars == res, na.rm = TRUE)
          inc_res_c[i] <- mean(data_year_i_pol$inc_res_bars == res, na.rm = TRUE)
        }
        data_year_i <- 
          data_frame(kom   = kom, 
                     year  = k, 
                     label = lab[j], 
                     rep   = sum(par_inc_c * 1:20) - sum(par_inc_m * 1:20),
                     comp  = sum(inc_res_c * seq(-3, 3, 0.5)) - sum(inc_res_m * seq(-3, 3, 0.5)))
      
      data_out <- 
        bind_rows(data_out, data_year_i)
      }
    }
  }
  print(k)
  print(Sys.time())
}

data_cand <-
  data_out %>% 
  filter(label == "local candidate" & !is.na(rep)) 

data_win <-
  data_out %>% 
  filter(label == "local winner" & !is.na(rep)) 

# find slope coefficients
mod1 <- lm(comp ~ rep, data = data_cand)
mod2 <- lm(comp ~ rep, data =  data_win)

data_cand <-
  data_cand %>% 
  mutate(reptile  = ntile(rep, floor(nrow(.)/50))) 

data_win <-
  data_win %>% 
  mutate(reptile  = ntile(rep, floor(nrow(.)/50))) 

label1 <- 
  paste("Running for municipality \nb=",
        round(coef(mod1)[2], 3),
        "(",
        round(summary(mod1)$coefficients[2,2], 3), 
        ") beta=",
        round(coef(lm.beta(mod1))[2], 3),
        sep = "")

label2 <- 
  paste("Elected for municipality \nb=",
        round(coef(mod2)[2], 3),
        "(",
        round(summary(mod2)$coefficients[2,2], 3), 
        ") beta=",
        round(coef(lm.beta(mod2))[2], 3),
        sep = "")

data_rep <- 
  bind_rows(data_win, data_cand) %>% 
  group_by(label, reptile) %>% 
  summarise(rep_mean  = mean(rep, na.rm = TRUE),
            comp_mean = mean(comp, na.rm = TRUE)) %>% 
  ungroup() %>%
  mutate(label = as.factor(ifelse(label == "local candidate", label1, label2)),
         label = factor(label, levels = levels(label)[c(2,1)])) 

data_lines <- 
  data_frame(slope = c(coef(lm(comp ~ rep, data = data_cand))[2],
                       coef(lm(comp ~ rep, data =  data_win))[2]),
             inter = c(coef(lm(comp ~ rep, data = data_cand))[1],
                       coef(lm(comp ~ rep, data =  data_win))[1]),
             label = as.factor(c(label1, label2)))

plot <- 
  ggplot(data = data_rep,
         aes(x = rep_mean, 
             y = comp_mean)) + 
  geom_point() + 
  facet_grid(. ~ label) + 
  theme_classic() +
  scale_y_continuous("Earnings score index") +
  scale_x_continuous("") + 
  theme(panel.spacing = unit(2, "lines")) +
  geom_abline(data = data_lines, 
              aes(slope = slope,
                  intercept = inter),
              linetype = "dashed",
              alpha = 0.6)